import { subscribeWithSelector } from 'zustand/middleware'
import create from 'zustand'
import { ISelectUser, StateStore } from './interface'
import dayjs from '@/plugins/dayjs'

import { useCreateContentStore } from '../../store'
import { FetchAllMeetingDetail } from '@/api/create/interface'
import { fetchCheckMeetingName } from '@/api/manager/meetingInfoSet'
import { getDayAndStartTime, transRoomData, transSelectUserItem } from './translator'
import { FetchTemplateParams } from '@/api/template/interface'
import { t } from 'i18next'

type IStore = StateStore & {
	update: (d: Partial<StateStore>) => void
	reset: () => void
	init: (
		data: { isTemplate: false; model: FetchAllMeetingDetail } | { isTemplate: true; model: FetchTemplateParams }
	) => void
	/** 校验名称重复性 */
	checkMeetingName: () => Promise<boolean>
}

const initUser: ISelectUser = {
	account: '',
	account_type: 1,
	name: t('无'),
	uid: '',
}

const getDayAndStartTimeValue = () => {
	return getDayAndStartTime(dayjs().format('YYYY-MM-DD'), dayjs().format('HH:mm'))
}

const initialState: StateStore = {
	name: '',
	mobilePhone: '',
	phoneNO: '',
	day: getDayAndStartTimeValue().day,
	startTime: getDayAndStartTimeValue().startTime,
	hour: 4,
	minute: 0,
	permanentMeeting: false,
	repeat: false,
	superMtNum: false,
	meetingFormular: null,
	fileNumber: 0,
	brief: '',
	notifyMode: {
		sms: false,
		email: true,
		wechat: true,
	},
	preAssignedMeetingCheck: false,
	preAssignedMeetingNumber: '',
	speaker: initUser,
	manager: initUser,
	speakerList: [initUser],
	managerList: [initUser],
	vipList: [],
	meetingCriteriaList: [],
	roomData: null,
	_isSearchRoomDialogShow: false,
	_isRepeatDialogShow: false,
	_isImportTemplateShow: false,
	_isMeetingFileShow: false,
	_errorMsg: '',
	isInit: true,
}

export const useBasicInfoStore = create<IStore>()(
	subscribeWithSelector((set, get) => ({
		...initialState,
		update: (d) => set({ ...d }),
		reset: () => set(initialState),
		init: ({ isTemplate, model }) => {
			if (!isTemplate) {
				model = model as FetchAllMeetingDetail
				set({
					name: model.name ?? '',
					mobilePhone: model.mobile ?? '',
					phoneNO: model.telephone ?? '',
					day: dayjs(model.start_time).format('YYYY-MM-DD'),
					startTime: dayjs(model.start_time).format('HH:mm'),
					hour: model.duration === 0 ? 4 : Math.floor(model.duration / 60),
					minute: model.duration === 0 ? 0 : model.duration % 60,
					permanentMeeting: model.duration === 0,
					repeat: !model.regular_meeting_moid && model.meeting_formular ? true : false,
					superMtNum: !!model.enable_audience,
					meetingFormular:
						!model.regular_meeting_moid && model.meeting_formular
							? { endTime: model.meeting_formular.end_date, weekDays: model.meeting_formular.week_days }
							: null,
					fileNumber: model.file_num ?? 0,
					brief: model.brief ?? '',
					notifyMode: {
						sms: !!model.sms,
						email: !!model.email,
						wechat: !!model.wechat,
					},
					speaker: model.speaker ? transSelectUserItem(model.speaker) : initUser,
					manager: model.chairman ? transSelectUserItem(model.chairman) : initUser,
					vipList: model.vips ?? [],
					meetingCriteriaList: model.meeting_criteria_list ?? null,
					roomData: model.room_static ? transRoomData(model.room_static) : null,
					isInit: false,
				})
			} else {
				model = model as FetchTemplateParams
				set({
					name: model.name ?? '',
					mobilePhone: model.mobile ?? '',
					phoneNO: model.telephone ?? '',
					hour: model.duration === 0 ? 4 : Math.floor(model.duration / 60),
					minute: model.duration === 0 ? 0 : model.duration % 60,
					permanentMeeting: model.duration === 0,
					superMtNum: !!model.enable_audience,
					preAssignedMeetingCheck: !!model.e164,
					preAssignedMeetingNumber: model.e164 ?? '',
					speaker: model.speaker ? transSelectUserItem(model.speaker) : initUser,
					manager: model.chairman ? transSelectUserItem(model.chairman) : initUser,
					vipList: model.vips ?? [],
					isInit: false,
				})
			}
		},
		checkMeetingName: async () => {
			const { day, startTime, permanentMeeting, hour, minute, name, update } = get()
			const isTemplate = useCreateContentStore.getState().isTemplate
			let _startTime = day + ' ' + startTime + ':00'
			let _endTime = permanentMeeting
				? undefined
				: dayjs(_startTime)
						.add(hour * 60 + minute, 'minute')
						.format('YYYY-MM-DD HH:mm:ss')
			let res = await fetchCheckMeetingName({
				conf_name: name,
				end_time: _endTime ? dayjs(_endTime).format() : undefined,
				start_time: dayjs(_startTime).format(),
				meeting_id: useCreateContentStore.getState().meetingMoid,
			})
			if (!res) {
				update({ _errorMsg: isTemplate ? t('模板名称已存在') : t('会议名称已存在') })
			} else {
				update({ _errorMsg: null })
			}
			return res
		},
	}))
)
